//
//  WorkListViewController.m
//  Patrol
//
//  Created by Lee on 13-2-26.
//  Copyright (c) 2013年 FSTI. All rights reserved.
//

#import "WorkListViewController.h"
#import "PlanListViewController.h"
#import "MBProgressHUD.h"
#import "PatrolServiceClient.h"
#import "WorkListCell.h"
#import "FWAppDelegate.h"
#import "SVPullToRefresh.h"

@interface WorkListViewController ()

@end

@implementation WorkListViewController
- (void)searchPlain:(NSString *)workID{
    PlanListViewController *next = [[PlanListViewController alloc] initWithNibName:@"PlanListViewController" bundle:nil];
    next.title = @"作业计划";
    next.plainListID = workID;
//    next.list = plainArray;
    [self.navigationController pushViewController:next animated:YES];
    
        
}
- (void) pageTurn:(WorkListViewController *)work pageNumber:(NSInteger)pageNumber pageSize:(NSInteger)pageSize{
    
    FWAppDelegate *appDelegate = (FWAppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *userName = appDelegate.userName;
    PatrolServiceClient * client = [PatrolServiceClient shareInstance];
    if (client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi || client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
        [client searchAll:userName pageSize:pageSize pageNumber:pageNumber resultBlock:^(id outJson, NSError *error) {
            if (!outJson && error!=nil) {
                DLog(@"Threre is somethings wrong ");
                return ;
            }
            NSDictionary *results = outJson;
            NSArray *workArray = [results objectForKey:@"list"];;
            work.list = workArray;
            [work.tableView reloadData];
            [work.tableView.pullToRefreshView stopAnimating];
            [work.tableView.infiniteScrollingView stopAnimating];
            NSIndexPath *idxPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [work.tableView scrollToRowAtIndexPath:idxPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
            [work hudShow:[NSString stringWithFormat:@"第%d页",work.pageNumber] view:work.navigationController.view];
        }];
    }else{
        [UIUtil alertOKWithTitle:@"错误" withMsg:@"当前没有连接任何网络" withDelegate:self];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        return;
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([_list count] > 0) {
        [_isEmpty setHidden:YES];
    }
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    if (_isPage) {
        __weak WorkListViewController *work = self;
        _pageSize = 20;
        _pageNumber = 1;
        //下拉 获取上一页
        [self.tableView addPullToRefreshWithActionHandler:^{
            if (work.pageNumber > 1) {
                work.pageNumber = work.pageNumber - 1;
                [work pageTurn:work pageNumber:work.pageNumber pageSize:work.pageSize];
            }else{
                [work hudShow:@"已经是首页" view:work.navigationController.view];
                [work.tableView.pullToRefreshView stopAnimating];
            }
        }];
        
        [self.tableView addInfiniteScrollingWithActionHandler:^{
            work.pageNumber = work.pageNumber + 1;
            NSInteger number = work.allCount / work.pageSize;
            NSInteger remainder = work.allCount % work.pageSize;
            if (remainder > 0) {
                number = number + 1;
            }
            if (work.pageNumber > number) {
                [work hudShow:@"已经是末页" view:work.navigationController.view];
                [work.tableView.infiniteScrollingView stopAnimating];
            }else{
                [work pageTurn:work pageNumber:work.pageNumber pageSize:work.pageSize];
            }
        }];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    PatrolServiceClient * client = [PatrolServiceClient shareInstance];
    [client cancelHttpRequest:kSearchAllPath];
    [client cancelHttpRequest:kSearchPlainPath];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"WorkListCellIdentifier";
    WorkListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"WorkListCell" owner:self options:nil];
        if ([array count] > 0) {
            cell = [array lastObject];
        }
    }
    NSUInteger row = [indexPath row];
    NSDictionary *rowDictionary = [_list objectAtIndex:row];
    NSString *work_desc = [rowDictionary objectForKey:@"work_desc"];
    NSString *work_number = [NSString stringWithFormat:@"%@",[rowDictionary objectForKey:@"number"]];
    [cell setCellContent:work_desc Number:work_number];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.backgroundColor = [UIColor clearColor];
    NSUInteger row = [indexPath row];
    UIView *v = [[UIView alloc] initWithFrame:cell.frame];
    if (row % 2) {
        v.backgroundColor = [UIColor whiteColor];
    }else{
        UIColor *backgroundColor = [UIColor colorWithRed:(251.0/255.0) green:(248.0/255.0) blue:(243.0/255.0) alpha:1.0];
        v.backgroundColor = backgroundColor;
    }
    cell.backgroundView = v;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *selected = [_list objectAtIndex:[indexPath row]];
    NSString *workID = [selected objectForKey:@"work_id"];
    [self searchPlain:workID];
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger row = [indexPath row];
    NSDictionary *rowDictionary = [_list objectAtIndex:row];
    NSString *work_desc = [rowDictionary objectForKey:@"work_desc"];
    return [WorkListCell calcLabelHeightForString:work_desc] + 22;
}

#pragma mark -
#pragma mark - Util Methods

- (void)hudShow:(NSString *)message view:(UIView *)view{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = message;
    hud.margin = 10.f;
    hud.yOffset = 60.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
}

- (void)viewDidUnload {
    [self setIsEmpty:nil];
    [super viewDidUnload];
}
@end
